<template>
  <div class="app-container">

    <el-container>
      <el-header style="height: auto; padding: 10px;">
        <el-row :gutter="20" type="flex" align="middle">
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="5">
            <el-select v-model="web_id" v-loading="websLoading" style="width: 100%" size="small" placeholder="输出站点" clearable filterable @change="handleSearchWPAccount">
              <el-option
                v-for="web in webs"
                :key="web.id"
                :label="web.url"
                :value="web.id"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="19">
            <el-row :gutter="20" type="flex" align="middle">
              <el-col :span="4">
                <el-select v-model="review_state" @change="handleSearch">
                  <el-option value="" label="所有" />
                  <el-option
                    v-for="item in review_states"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <!--                    <el-select-->
                <!--                        v-model="parent_id"-->
                <!--                        filterable-->
                <!--                        remote-->
                <!--                        reserve-keyword-->
                <!--                        placeholder="搜索父级ID"-->
                <!--                        :remote-method="remoteSearchParent"-->
                <!--                        :loading="parentIdLoading"-->
                <!--                        @change="handleSearch"-->
                <!--                        size="small"-->
                <!--                        style="width: 100%;"-->
                <!--                      >-->
                <!--                        <el-option-->
                <!--                          v-for="item in parentOptions"-->
                <!--                          :key="item.value"-->
                <!--                          :label="item.label"-->
                <!--                          :value="item.value">-->
                <!--                        </el-option>-->
                <!--                      </el-select>-->
              </el-col>
              <el-col :span="8">
                <el-input v-model="kwInput" size="small" placeholder="输入关键词进行筛选" clearable @keyup.native.enter="handleSearch">
                  <el-button slot="append" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                </el-input>
              </el-col>
            </el-row>
            <el-row :gutter="20" type="flex" align="middle">
              <el-col :span="6">
                <el-slider
                  v-model="progress"
                  range
                  :format-tooltip="progressToolTips"
                  :max="100"
                  @change="handleSearch"
                />
              </el-col>
              <el-col :span="6">
                <el-slider
                  v-model="stars"
                  range
                  :format-tooltip="starToolTips"
                  :min="1"
                  :max="5"
                />
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-alert
          v-if="accountAlertTitle.length"
          :title="accountAlertTitle"
          style="margin-top: 10px;"
          type="error"
        />
      </el-header>
      <el-container>
        <el-main>
          <el-table
            v-loading.body="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            style="width: 100%"
            :row-class-name="tableRowClassName"
            @cell-mouse-enter="(m) => m.active=true"
            @cell-mouse-leave="(m) => m.active=false"
            @selection-change="handleSelectionChange"
            @sort-change="handleSort"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column align="left" label="ID" prop="id" width="80" sortable="custom" />
            <el-table-column align="left" label="标题" prop="title" sortable="custom">
              <template slot-scope="scope">
                <span class="" :title="scope.row.title" @click="handleGetClickText">{{ scope.row.title }}</span>
                <span v-if="scope.row.category__name !== ''">{{ '[' + scope.row.category__name + ']' }}</span>
                <el-popover
                  placement="top-start"
                  title="详情"
                  width="400"
                  trigger="click"
                >
                  <el-descriptions title="" :column="1">
                    <el-descriptions-item label="PL">{{ scope.row.owner__username }}</el-descriptions-item>
                    <el-descriptions-item label="输出网站">{{ scope.row.web__name }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ scope.row.create_at }}</el-descriptions-item>
                  </el-descriptions>
                  <span slot="reference" style="float: right;display: inline-block;color:#dec9c9;margin-left: 5px;"><i class="el-icon-info" />{{ scope.row.update_at.split('T')[0] }}</span>
                </el-popover>
                <div v-if="scope.row.active" class="mt-row-btns">
                  <a class="mt-btn danger" title="删除框架" @click="handleClickDelete(scope.row)">
                    <i class="el-icon-delete mt-icon" /></a>
                  <a :class="scope.row.is_init ? 'mt-btn danger':'mt-btn default'" title="修改框架" @click="handleDirectlyEditTopic(scope.row)">
                    <i class="el-icon-edit mt-icon" />
                  </a>
                  <a class="mt-btn default" title="翻译标题" @click="handleTranslateTitle(scope.row)">
                    <i class="el-icon-connection mt-icon" />
                  </a>
                  <a v-if="scope.row.post_id === ''" class="mt-btn default" title="添加post" @click="handleAddPost(scope.row)">
                    <i class="el-icon-document-add mt-icon" /></a>
                  <a v-else class="mt-btn danger" title="编辑post" @click="handleEditPost(scope.row)">
                    <i class="el-icon-document mt-icon" /></a>
                  <a :class="scope.row.serp_finished ? 'mt-btn danger':'mt-btn default'" title="素材" @click="handleAddMaterial(scope.row)">
                    <i class="el-icon-folder-add mt-icon" /></a>
                  <a v-if="scope.row.post_url !== ''" class="mt-btn danger" title="打开博客" :href="scope.row.post_url" target="_blank">
                    <i class="el-icon-link mt-icon" /></a>
                  <a class="mt-btn danger" title="暂时不发" @click="handleSetProgress(scope.row, 77)">
                    <i class="el-icon-circle-close mt-icon" /></a>
                </div>
                <span v-if="scope.row.owner_pass" style="float: right; color: green;">可发</span>
                <span v-else-if="scope.row.post__writer_finished" style="float: right; color: red;">优化完</span>
                <el-tag v-if="scope.row.tag.indexOf('http') !== -1 || scope.row.tag === 'cache_blog' || scope.row.tag === 'runskyblog'" style="float: right;">[推广]</el-tag>
                <el-tag v-if="scope.row.auto_post_account_id" style="float: right;" type="warning">[自动]</el-tag>
              </template>
            </el-table-column>
            <!--            <el-table-column align="left" label="VOL" prop="volume" sortable="custom" width="80"></el-table-column>-->
            <!--            <el-table-column align="left" label="KD" prop="difficulty" sortable="custom" width="80"></el-table-column>-->
            <!--            <el-table-column align="center" label="完成进度" prop="progress" width="160" sortable="custom">-->
            <!--              <template slot-scope="scope">-->
            <!--                <el-progress @click="handleModifyProgress(scope.row)" v-if="scope.row.progress < 100"-->
            <!--                             :percentage="scope.row.progress"></el-progress>-->
            <!--                <el-progress @click="handleModifyProgress(scope.row)" v-else :percentage="100" status="success"></el-progress>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="关键词" prop="keyword" width="160" sortable="custom">-->
            <!--              <template slot-scope="scope">-->
            <!--                <span v-if="scope.row.keyword !== ''" @click="handleOpenReviews(scope.row)">{{scope.row.keyword}}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            // 审核状态，如果是草稿，按钮时，请求审核，如果是等待审核 则按钮时通过审核
            <el-table-column align="center" label="审核状态" prop="status" width="360" sortable="custom">
              <template slot-scope="scope">
                <el-button v-if="scope.row.status === 'draft'" size="mini" type="primary" @click="handleSaveQuickEditTopic(scope.row, 'status', 'pending')">提交审核</el-button>
                <div v-else-if="scope.row.status === 'pending'">
                  <el-tag v-if="roles.indexOf('topic_manager') === -1" type="warning">待审核</el-tag>
                  <div v-else>
                    <el-button size="mini" type="success" @click="handleSaveQuickEditTopic(scope.row, 'status', 'approved')">通过审核</el-button>
                    <el-button size="mini" type="danger" @click="handleSaveQuickEditTopic(scope.row, 'status', 'rejected')">拒绝通过</el-button>
                  </div>
                </div>
                <div v-else-if="scope.row.status === 'rejected'">
                  <el-alert v-if="scope.row.review_comment !== ''" size="mini" type="error" :title="scope.row.review_comment" />
                  <el-button size="mini" type="primary" @click="handleSaveQuickEditTopic(scope.row, 'status', 'pending')">再次提交</el-button>
                </div>

                <el-tag v-else type="success">已经通过</el-tag>
              </template>
            </el-table-column>
            <!-- star栏已隐藏 -->

            <!--            <el-table-column align="center" label="作者" prop="owner__name" width="210" sortable="custom">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ scope.row.owner__username }}|{{ scope.row.project__name }}-->
            <!--                <br>-->
            <!--                {{ scope.row.web__name }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="最后更新" prop="update_at" sortable="update_at" width="180px">-->
            <!--              <template slot-scope="scope">-->
            <!--                  {{scope.row.update_at.split('T')[0]}}-->
            <!--              </template>-->
            <!--            </el-table-column>-->

          </el-table>
          <el-pagination
            v-if="data.length"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10, 15,20,50,100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
          <div v-if="drawer_data.length" style="margin-top: 10px; float: left; display: flex; gap: 10px;">
            <el-button type="primary" size="mini" @click="showMutliEdit">批量设置</el-button>
            <el-button
              size="mini"
              style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
              icon="el-icon-check"
              @click="handleBatchReviewApprove"
            >批量通过</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-close"
              @click="handleBatchReviewReject"
            >批量拒绝</el-button>
            <span style="color: #909399; font-size: 12px; line-height: 28px;">已选择 {{ drawer_data.length }} 项</span>
          </div>
          <topicstrategy :web-visible="webVisible" @closeWebDialog="webVisible=false" />
        </el-main>
      </el-container>
    </el-container>
    <el-dialog
      v-loading.fullscreen.lock="deleteDialogLoading"
      :title="deleteDialogTitle"
      :visible.sync="deleteDialogVisible"
      style="margin-top: 148px !important;"
    >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="handleDeleteConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="postsdataDialogTitle"
      :visible.sync="postsdataDialogVisible"
      style="margin-top: 148px !important;"
    >
      <el-table :data="postsdata">
        <el-table-column align="center" label="标题" prop="title">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <a :href="scope.row.post_url" target="_blank" style="flex: 1; text-align: left;">{{ scope.row.title }}</a>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-search"
                circle
                title="Google搜索此标题"
                style="margin-left: 10px;"
                @click="handleGoogleSearchTitle(scope.row.title)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="postsdataDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-drawer
      :wrapper-closable="false"
      :title="titleTopicDialog"
      :visible.sync="titleTopicDialogVisible"
      :close-on-click-modal="false"
      style="margin-top: 10px !important;"
      size="90%"
    >
      <div style="margin: 10px">
        <el-form ref="dataForm" :model="topicTemp" label-position="left" label-width="100px">
          <el-form-item label="title">
            <el-input v-model="topicTemp.title" />
          </el-form-item>
          <el-form-item label="keyword">
            <el-input v-model="topicTemp.keyword" />
          </el-form-item>
          <el-form-item label="AI段落数量">
            <el-input v-model="topicTemp.ai_paragraph" />
          </el-form-item>
          <el-form-item label="内容优先级">
            <el-rate
              v-model="topicTemp.star"
              :texts="['最低', '很低', '一般', '很高', '最高']"
              show-text
            />
          </el-form-item>
          <el-form-item label="文章类型">
            <el-select v-model="topicTemp.category_id" placeholder="文章类型" size="mini" class="head" clearable>
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="进度">
            <el-input v-model="topicTemp.progress" style="width: 100px; display: inline-block" size="mini" placeholder="进度" type="number" />
            <el-progress :percentage="topicTemp.progress" style="display: inline-block; width: 250px" />
          </el-form-item>
          <el-form-item label="内容">
            <!--          <tinymce ref="mt" :height="300" v-model="topicTemp.description"></tinymce>-->
            <!--          <simplemde-md :id="md_id" :value="topicTemp.description" placeholder="markdown标记" style="display: block"></simplemde-md>-->
            <el-input v-model="topicTemp.description" style="max-height: 400px" type="textarea" rows="5" placeholder="# 一级标题 ## 二级标题 注意#号于内容质检有个空格" />
          </el-form-item>

          <el-form-item label="其他参数">

            <!--        <el-form-item label="keyword" >-->
            <span style="margin-left: 10px">TAG:<el-input v-model="topicTemp.tag" size="mini" style="width: 200px" /></span>
            自动发布设置:
            <el-tag v-if="topicTemp.auto_post_account_id">wp账号:{{ topicTemp.auto_post_account_id }} | {{ post_domain }} </el-tag>
            <el-tag v-if="topicTemp.auto_post_category">目录id:{{ topicTemp.auto_post_category }} </el-tag>
            <el-tag v-if="topicTemp.auto_post_tags">tag:{{ topicTemp.auto_post_tags }} </el-tag>
            <el-row>
              博客:
              <el-select
                v-model="topicTemp.web_id"
                v-loading="websLoading"
                size="mini"
                placeholder="输出站点"
                clearable
                filterable
                style="width: 300px;"
              >
                <el-option
                  v-for="web in webs"
                  :key="web.id"
                  :label="web.url"
                  :value="web.id"
                />
              </el-select>
              写手:
              <el-select v-model="topicTemp.writer_id" placeholder="指定写手" size="mini" filterable clearable style="width: 150px;">
                <el-option label="不指定" value="" />
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.show_name"
                  :value="user.id"
                />
              </el-select>
            </el-row>
            <el-row style="margin-top: 10px" :gutter="40">
              <el-col :span="12">
                爬取素材:<el-switch
                  v-model="topicTemp.serp_crawl"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
                <span style="margin-left: 10px">完成:</span><el-switch
                  v-model="topicTemp.serp_finished"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-col>

            </el-row>
          </el-form-item>
        </el-form>
        <div class="drawer-footer" style="padding: 20px; text-align: right; border-top: 1px solid #e8e8e8; margin-top: 20px;">
          <el-button style="float: left" @click="handleShowMaterial()">查看素材</el-button>
          <el-button v-if="topicViewData.post_id" type="danger" style="display: inline-block; margin-right: 10px;" @click="handleRewrite()">重写</el-button>
          <el-button @click="handleCleanTopicForm">清空内容</el-button>
          <el-button @click="titleTopicDialogVisible = false; topicEditId = ''">取 消</el-button>
          <el-button type="primary" @click="handleAddTopic">保 存</el-button>
        </div>
      </div>
    </el-drawer>

    <el-dialog
      :title="titleTopicViewDialog"
      :visible.sync="TopicViewDialogVisible"
      style="margin-top: 10px !important;"
    >
      <h3>{{ topicViewData.title }}</h3>
      <hr>
      <div style="display: block; font-size: 14px;max-height: 438px" v-html="topicViewData.description" />

      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="HanldeEditTopic">编 辑</el-button>
        <el-button @click="TopicViewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="批量修改话题"
      :visible.sync="multiTopicsEditorVisible"
      style="margin-top: 10px !important;"
    >
      <el-divider content-position="center">每一个参数单独修改</el-divider>
      <el-form ref="dataForm" :model="topicTemp" label-position="left" label-width="100px">
        <el-form-item label="优先级">
          <el-rate
            v-model="topicTemp.star"
            style="display: inline-block"
            :texts="['最低', '很低', '一般', '很高', '最高']"
            show-text
          />
          <el-button type="danger" size="mini" @click="handleMultiModify('star')">提交修改</el-button>
        </el-form-item>
        <el-form-item label="AI控制">
          <el-row :gutter="2">
            <el-col :span="4">
              段落:
              <el-input v-model="topicTemp.ai_paragraph" style="width: 70%" title="输入段落数量" size="mini" placeholder="段落数量" />
            </el-col>
            <el-col :span="12">
              AI:
              <el-select v-model="topicTemp.ai_writer" placeholder="AI类型" size="mini" class="head" clearable>
                <el-option
                  v-for="item in ai_writers"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
          </el-row>
          <el-button type="danger" size="mini" @click="handleMultiModify('ai')">批量修改</el-button>
        </el-form-item>
        <el-form-item label="推广/tag:">
          <span><el-input v-model="topicTemp.tag" size="mini" style="width: 200px" /></span>
          <el-button type="success" size="mini" @click="handleMultiModify('tag')">提交</el-button>
        </el-form-item>
        <el-form-item label="父级ID">
          <span><el-input v-model="topicTemp.parent_id" size="mini" style="width: 200px" /></span>
          <el-button type="success" size="mini" @click="handleMultiModify('parent_id')">提交</el-button>
        </el-form-item>
        <el-form-item label="progress">
          <el-slider
            v-model="topicTemp.progress"
            style="width: 200px;display: inline-block; margin: auto;"
            :max="100"
          />
          <el-button type="danger" size="mini" @click="handleMultiModify('progress')">提交</el-button>
        </el-form-item>

        <el-form-item label="SERP">
          <el-switch
            v-model="topicTemp.serp_crawl"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <el-button type="danger" size="mini" @click="handleMultiModify('serp')">提交</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="multiTopicsEditorVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-drawer
      :wrapper-closable="false"
      :title="topic_title"
      :visible.sync="topicmaterialDrawerVisible"
      direction="rtl"
      @close="materialVisible=false"
    >
      <topicmaterial
        :topic_id="topic_id"
        :topic_title="topic_title"
        :web-visible="materialVisible"
        @closeMetrialDialog="materialVisible=false"
      />
    </el-drawer>
    <el-drawer
      :wrapper-closable="false"
      title="对比视图"
      size="90%"
      style="max-height: 100%"
      :visible.sync="drawer"
      direction="btt"
    >
      <el-card v-for="(item,index) in drawer_data" :key="index" class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ item.title }}</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="handleDirectlyEditTopic(item)">编辑</el-button>
        </div>
        <div v-html="item.description" />
      </el-card>
    </el-drawer>
    <!--    <topicmaterial :topic_id="topic_id" :topic_title="topic_title" :webVisible="materialVisible"-->
    <!--                   @closeMetrialDialog="materialVisible=false"></topicmaterial>-->
    <topicpost
      :topic_id="topic_id"
      :topic_title="topic_title"
      :web-visible="postVisible"
      @closeMetrialDialog="postVisible=false"
    />

    <!-- 浮动按钮 -->
    <el-button
      type="primary"
      icon="el-icon-search"
      circle
      size="large"
      class="floating-search-btn"
      title="Google搜索选中标题"
      @click="handleGoogleSearch"
    />
    <web :web-visible="webVisible" @reload="handleFetchWebs" @closeWebDialog="webVisible=false" />
    <post_editor :post_id="edit_post_id" :post-editor-visible="postEditorVisible" @close="handleEditPostClose" />
    <el-dialog
      title="请输入驳回原因"
      :visible.sync="rejectDialogVisible"
      width="30%"
    >
      <el-autocomplete
        v-model="rejectReason"
        class="inline-input"
        :fetch-suggestions="queryRejectReasons"
        placeholder="请输入驳回原因"
        style="width: 100%"
        @select="handleSelectReason"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { Get as GetProjects } from '@/api/erp/elicink/project'
import { Get as Getstrategies } from '@/api/cms/topicstrategy'
import { Get as GetCategories } from '@/api/cms/category'
import { Put, Delete, Post as AddTopic, Get as GetTopics, topic_crawl_amazon_toggle, Tree as GetTopicTree, BatchUpdateReviewState } from '@/api/cms/topic'
import { Get as GetWPAccount } from '@/api/cms/wpaccount'
import { Get as GetUsers } from '@/api/users'
import clip from '@/utils/clipboard' // use clipboard directly
import topicstrategy from '@/views/cms/elements/topicstrategy'
import topicmaterial from '@/views/cms/elements/topicmaterial'
import topicpost from '@/views/cms/elements/topicpost'
import { Get as GetWebs } from '@/api/cms/web'
// import Tinymce from '@/components/Tinymce'
import qs from 'qs'
const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

import Cookies from 'js-cookie'
import Web from './elements/web'
import Post_editor from './elements/posteditor'
// import SimplemdeMd from "../../components/MarkdownEditor/index";
import { Translate } from '@/api/crm/crmmanage'

const ProjectKey = 'cms_project_id__search'
const StrotegyKey = 'cms_strategy_id__search'
const TopicKeywordKey = 'cms__keyword__search'
const OwnerKey = 'cms_language_id__owner'
const webIdKey = 'cms_web_id'
export function SelectText() {
  try {
    var se = window.getSelection().toString()
    if (se != null && se.trim() !== '') {
      return se.trim()
    } else {
      return ''
    }
  } catch (err) {
    var s2 = document.selection.createRange()
    var s = s2.text
    if (s != null && s.trim() !== '') {
      return se.trim()
    } else {
      return ''
    }
  }
}
export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function getTokenStr(key) {
  const v = Cookies.get(key)
  return v || null
}

export function setToken(key, value) {
  if (value) {
    return Cookies.set(key, value)
  }
}

export default {
  components: { Post_editor, Web, topicstrategy, topicmaterial, topicpost },
  data() {
    return {
      /*     REVIEW_STATUS = (
        ('draft', '草稿'),
        ('pending', '待审核'),
        ('approved', '已通过'),
        ('rejected', '已驳回')
    )
         */
      review_states: [{
        value: 'draft',
        label: '草稿'
      }, {
        value: 'pending',
        label: '待审核'
      }, {
        value: 'approved',
        label: '已通过'
      }, {
        value: 'rejected',
        label: '已驳回'
      }
      ],
      review_state: 'pending',
      project_id: this.$store.getters.projectId,
      categories: [],
      accountAlertTitle: '',
      wpaccont_domian: '',
      postsdataDialogTitle: '查询已发帖',
      postsdataDialogVisible: false,
      postsdata: [],
      poststotal: 0,
      edit_post_id: '',
      postEditorVisible: false,
      md_id: 1,
      stars: [1, 5],
      progress: [1, 95],
      marks: {
        10: '10',
        70: '70',
        90: '90',
        99: '99'
      },
      star: 1,
      drawer_data: [],
      drawer: false,
      activeToolName: '1',
      topicMateiralTemp: {
        title: '',
        note: ''
      },
      postVisible: false,
      materialVisible: false,
      topicmaterialDrawerVisible: false,
      // titleTopicMaterialDialog: '',
      // titleTopicMaterialDialogVisible: false,
      topic_id: '',
      topic_title: '框架素材',
      dataMaterial: [],
      TopicViewDialogVisible: false,
      titleTopicViewDialog: '查看内容',
      topicViewData: {
        title: '',
        parent_id: '',
        description: '',
        tag: '',
        strategy_id: '',
        keyword: '',
        progress: 0
      },
      topicEditId: '',
      titleTopicDialog: '添加新框架',
      titleTopicDialogVisible: false,
      topicTemp: {
        title: '',
        star: 1,
        web_id: '',
        ai_paragraph: 3,
        parent_id: '',
        serp_crawl: false,
        serp_finished: false,
        project_id: '',
        description: '# 一级标题(h1)\n## 二级标题(h2)\n### 三级标题(h3)\n#### 四级标题h4\n注意#号和内容要有空格,每行一个标题\n' +
            'AI内容+随机抓取内容:{random}\n纯随机抓取:{random-only}\n关键词替换:[keyword]',
        tag: '',
        strategy_id: '',
        category_id: '3',
        auto_post_account_id: '',
        auto_post_category: '',
        auto_post_tags: '',
        writer_id: '',
        keyword: '',
        progress: 0
      },
      ai_writers: [
        {
          label: 'openai',
          value: 'openai'
        },
        {
          label: '自动AI',
          value: 'autoai'
        },
        {
          label: '随机组合',
          value: 'random_article'
        },
        {
          label: '混合内容',
          value: 'mix_article'
        },
        {
          label: '不写',
          value: ''
        }

      ],
      listLoading: false,
      webVisible: false,
      projectsLoading: false,

      strategies: [],
      strategy_id: null,
      strategysLoading: false,

      languages: [],
      language_id: null,
      languagesLoading: false,

      users: [],
      owner_id: null,
      ownersLoading: false,

      webs: [],
      web_id: '',
      websLoading: false,

      title: '',
      content: '',
      saveDisabled: false,
      init_text: '',

      kwInput: '',
      parent_id: '',
      parentOptions: [],
      parentIdLoading: false,
      TagInput: '',
      keyword: '',
      more_filter: false,
      data: [],
      order_by: 'progress',
      order_desc: '1',
      // pagination
      pagesize: 15,
      page: 1,
      total: 0,
      m_active: false,
      deleteDialogVisible: false,
      deleteDialogTitle: '',
      deleteId: null,
      deleteDialogLoading: false,
      multiTopicsEditorVisible: false,
      rejectDialogVisible: false,
      rejectReason: '',
      rejectReasonField: '',
      rejectReasonRow: null,
      rejectReasonValue: '',
      rejectReasons: [
        { value: '标题没有搜索需求，请重新判断搜索意图:https://runsky.notion.site/192e694acab380adbea4faf582397827' },
        { value: 'AI标题,请重新思考用户需求' },
        { value: '论文式标题，不要使用大而全的内容标题' },
        { value: '主题太小，无法形成一篇文章' },
        { value: '重复标题，已经写过该话题' },
        { value: '主题太偏C端用户需求，且与目标关键词关联度不高' },
        { value: '标题过于复杂，不直接。' }
      ]
    }
  },
  computed: {
    projects() {
      return this.$store.getters.projects || []
    },
    roles() {
      return this.$store.getters.roles || []
    }
  },
  watch: {
    project_id(newValue, oldValue) {
      if (newValue !== oldValue) {
        // 当 projectId 改变时执行的操作
        this.getList()
      }
    }

  },
  created() {
    this.materialVisible = true
    this.project_id = this.$store.getters.projectId
    this.owner_id = getToken(OwnerKey)
    // this.keyword = getTokenStr(TopicKeywordKey)
    this.web_id = getToken(webIdKey)
    this.topicTemp.web_id = getToken(webIdKey)
    this.topicTemp.project_id = this.project_id
    // this.handleFetchProjects()
    this.handleFetchCategories()
    this.handleFetchGetUsers()
    this.handleFetchWebs()
    // this.getList()
    this.materialVisible = false
    this.remoteSearchParent('')
  },
  methods: {
    remoteSearchParent(query) {
      if (query !== '') {
        this.parentIdLoading = true
        GetTopicTree(null, qs.stringify({
          kw: query,
          pagesize: 10, // 限制返回结果数量
          page: 1
        }))
          .then(response => {
            this.parentIdLoading = false
            this.parentOptions = response.data.data.map(item => ({
              value: item.id,
              label: item.keyword + ' (ID: ' + item.id + ')'
            }))
          })
          .catch(e => {
            this.parentIdLoading = false
            console.error('搜索父级ID时出错:', e)
            this.$message.error('搜索父级ID失败，请重试')
          })
      } else {
        this.parentOptions = []
      }
    },
    showMutliEdit() {
      this.multiTopicsEditorVisible = true
    },
    handleBatchReviewApprove() {
      if (!this.drawer_data.length) {
        this.$message.warning('请先选择要操作的话题')
        return
      }

      this.$confirm(`确定要将选中的 ${this.drawer_data.length} 个话题设置为"已通过"吗？`, '批量审核确认', {
        confirmButtonText: '确定通过',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.executeBatchReview('approved')
      })
    },
    handleBatchReviewReject() {
      if (!this.drawer_data.length) {
        this.$message.warning('请先选择要操作的话题')
        return
      }

      this.$confirm(`确定要将选中的 ${this.drawer_data.length} 个话题设置为"已驳回"吗？`, '批量审核确认', {
        confirmButtonText: '确定拒绝',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.executeBatchReview('rejected')
      })
    },
    async executeBatchReview(reviewState) {
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在批量更新审核状态...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const topicIds = this.drawer_data.map(item => item.id)
        const response = await BatchUpdateReviewState({
          topic_ids: topicIds,
          review_state: reviewState
        })

        if (response.success) {
          this.$message.success(`成功更新 ${topicIds.length} 个话题的审核状态`)
          // 清空选择并刷新列表
          this.drawer_data = []
          this.getList()
        } else {
          this.$message.error(response.msg || '批量更新失败')
        }
      } catch (error) {
        console.error('批量审核失败:', error)
        this.$message.error('批量更新失败，请稍后重试')
      } finally {
        loadingInstance.close()
      }
    },
    handleMultiModify(task) {
      for (let i = 0; i < this.drawer_data.length; i++) {
        const data = {
          id: this.drawer_data[i].id
        }
        switch (task) {
          // eslint-disable-next-line no-case-declarations
          case 'star':
            data.star = this.topicTemp.star
            break
          case 'tag':
            data.tag = this.topicTemp.tag
            break
          case 'ai':
            data.ai_paragraph = this.topicTemp.ai_paragraph
            data.ai_writer = this.topicTemp.ai_writer
            break
          case 'progress':
            data.progress = this.topicTemp.progress
            break
          case 'serp':
            data.serp_crawl = this.topicTemp.serp_crawl
            break
          case 'parent_id':
            data.parent_id = this.topicTemp.parent_id
            break
        }
        if (data) {
          Put(data.id, data).then(response => {
            this.$message.success('修改id:' + data.id + '成功')
          }).catch(e => {
            this.$message.error('修改失败')
          })
        }
      }
    },
    handleFetchCategories() {
      GetCategories()
        .then(response => {
          this.categories = response.data.data
        })
        .catch(e => {
          this.$message.error('获取文章类型失败')
        })
    },
    handleRewrite() {
      Put(this.topicViewData.id, { 'id': this.topicViewData.id, 're_write': true }).then(response => {
        this.$message.success('修改成功')
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleSearchWPAccount() {
      this.accountAlertTitle = ''
      console.log('change id')
      if (this.web_id === '') {
        return
      }
      const filter_webs = this.webs.filter(item => item.id === this.web_id)
      if (filter_webs && filter_webs.length) {
        this.wpaccont_domian = filter_webs[0].url
      }
      this.getList()
      if (this.wpaccont_domian.length) {
        GetWPAccount(null, qs.stringify({
          kw: this.wpaccont_domian,
          auto_blog: false,
          pagesize: 1,
          page: 1
        }))
          .then(response => {
            const need_posts = response.data.data[0].daily_days * response.data.data[0].daily_post
            if (response.data.data[0].waiting_send < need_posts) {
              this.accountAlertTitle = '需要优化更多内容! 可优化:' + response.data.data[0].waiting_posts + '可发:' +
                    response.data.data[0].waiting_send + '周期内已发:' + response.data.data[0].today_post + ' 每' +
                    response.data.data[0].daily_days + '天发帖:' + response.data.data[0].daily_post + '[数据每小时更新一次]'
            }
          }).catch(err => {
            console.log(err)
          })
      }
    },
    handleGetClickText() {
      const keyword = SelectText()
      if (keyword.length > 0) {
        this.GetPostedTopics(keyword)
      }
    },
    handleEditPostClose() {
      this.postEditorVisible = false
      this.getList()
    },
    handleFetchWebs() {
      this.websLoading = true
      GetWebs(null, qs.stringify({ project_id: this.project_id }))
        .then(response => {
          this.websLoading = false
          this.webs = response.data.data
          if (this.webs.length) {
            this.web_id = getToken(webIdKey) || null
            this.handleSearchWPAccount()
          }
        })
        .catch(e => {
          this.websLoading = false
        })
    },
    changeWPAccount(v) {
      this.web_id = v
    },
    // handleFetchProjects() {
    //   this.projectsLoading = true
    //   GetProjects()
    //     .then(response => {
    //       this.projectsLoading = false
    //       this.projects = response.data.data
    //       if (this.projects.length) {
    //         this.project_id = getToken(ProjectKey) || null
    //       }
    //     })
    //     .catch(e => {
    //       this.projectsLoading = false
    //     })
    // },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleFetchstrategies() {
      this.strategysLoading = true
      this.strategy_id = ''
      Getstrategies(null, qs.stringify({ project_id: this.project_id }))
        .then(response => {
          this.strategysLoading = false
          this.strategies = response.data.data
          if (this.strategies.length) {
            // this.strategy_id = getToken(StrotegyKey) || null
            let inthelist = false
            let x
            for (x in this.strategies) {
              if (x.id === this.strategy_id) {
                inthelist = true
              }
            }
            if (!inthelist) {
              this.strategy_id = this.strategies[0].id
            }
          }
        })
        .catch(e => {
          this.strategysLoading = false
        })
    },
    handleFetchGetUsers() {
      this.ownersLoading = true
      GetUsers()
        .then(response => {
          this.ownersLoading = false
          this.users = response.data.data
          if (this.users.length) {
            this.owner_id = getToken(OwnerKey) || null
          }
        })
        .catch(e => {
          this.ownersLoading = false
        })
    },
    GetPostedTopics(keyword) {
      this.poststotal = 0
      GetTopics(null, qs.stringify({
        kw: keyword,
        progress_s: 100,
        progress_e: 100,
        pagesize: this.pagesize,
        page: this.page,
        star: this.star,
        order_by: this.order_by,
        order_desc: this.order_desc,
        owner_id: this.owner_id,
        project_id: this.project_id,
        web_id: this.web_id,
        strategy_id: this.strategy_id
      }))
        .then(response => {
          this.postsdata = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          if (this.postsdata.length === 0) {
            this.$message.warning(keyword + '没有匹配数据')
          } else {
            this.postsdataDialogTitle = keyword + '已经发帖' + response.data.total + '篇'
            this.postsdataDialogVisible = true
          }
        }).catch(e => {
          this.$message.error(keyword + '查询数据失败')
        })
    },
    getList(loading) {
      if (loading === undefined) {
        loading = true
      }
      this.listLoading = loading
      GetTopics(null, qs.stringify({
        kw: this.kwInput,
        review_state: this.review_state,
        parent_id: this.parent_id,
        progress_s: this.progress[0],
        progress_e: this.progress[1],
        keyword: this.keyword,
        tag: this.TagInput,
        min_star: this.stars[0],
        max_star: this.stars[1],
        pagesize: this.pagesize,
        page: this.page,
        star: this.star,
        order_by: this.order_by,
        order_desc: this.order_desc,
        owner_id: this.owner_id,
        project_id: this.project_id,
        web_id: this.web_id,
        strategy_id: this.strategy_id
      }))
        .then(response => {
          this.scrollTop()
          setToken(ProjectKey, this.project_id)
          // setToken(StrotegyKey, this.strategy_id)
          setToken(OwnerKey, this.owner_id)
          setToken(TopicKeywordKey, this.keyword)
          setToken(webIdKey, this.web_id)
          this.data = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          this.listLoading = false
          this.total = response.data.total
          // 如果为空，则提醒用户调整搜索条件
          if (this.data.length === 0) {
            this.$message.info('该进度范围没数据，可以适当调整进度')
          }
          this.drawer_data = this.data
        }).catch(e => {
          this.listLoading = false
          setToken(ProjectKey, this.project_id)
          setToken(StrotegyKey, this.strategy_id)
          setToken(OwnerKey, this.owner_id)
          setToken(TopicKeywordKey, this.keyword)
        })
    },
    handleAddNewTopic() {
      this.topicEditId = ''
      this.titleTopicDialogVisible = true
      // this.handleCleanTopicForm()
    },
    HanldeEditTopic() {
      this.topicTemp.title = this.topicViewData.title
      this.topicTemp.keyword = this.topicViewData.keyword
      this.topicTemp.star = this.topicViewData.star
      this.topicTemp.tag = this.topicViewData.tag
      this.topicTemp.ai_paragraph = this.topicViewData.ai_paragraph
      this.topicTemp.description = this.topicViewData.description
      this.topicTemp.progress = this.topicViewData.progress
      this.topicTemp.category_id = this.topicViewData.category_id
      this.topicTemp.auto_post_account_id = this.topicViewData.auto_post_account_id
      this.topicTemp.auto_post_category = this.topicViewData.auto_post_category
      this.topicTemp.auto_post_tags = this.topicViewData.auto_post_tags
      this.topicTemp.project_id = this.topicViewData.project_id
      this.topicTemp.web_id = this.topicViewData.web_id
      this.topicTemp.writer_id = this.topicViewData.writer_id
      this.topicTemp.parent_id = this.topicViewData.parent_id
      this.topicTemp.serp_finished = this.topicViewData.serp_finished
      this.topicTemp.serp_crawl = this.topicViewData.serp_crawl
      this.topicEditId = this.topicViewData.id
      this.titleTopicDialog = '编辑框架-' + this.topicViewData.title
      this.topicTemp.strategy_id = this.topicViewData.strategy_id
      this.TopicViewDialogVisible = false
      this.titleTopicDialogVisible = true

      // this.$nextTick(() => {
      //   this.$refs.mt.setContent(this.topicTemp.description)
      // })
    },
    handleToggleAmazonCrawlStatus(row) {
      if (row.keyword === '') {
        this.$message.error('关键词为空,修改无效')
        return
      }
      topic_crawl_amazon_toggle(row.id).then(response => {
        this.$message('修改成功')
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleChangeCrawlSerp(row) {
      console.log('progress clicked')
      this.topicEditId = row.id
      Put(this.topicEditId, { 'serp_crawl': row.serp_crawl }).then(response => {
        this.$message.success('修改成功')
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleModifyProgress(row) {
      console.log('progress clicked')
      this.topicTemp.title = row.title
      this.topicTemp.keyword = row.keyword
      this.topicTemp.tag = row.tag
      this.topicTemp.description = row.description
      this.topicTemp.progress = row.progress
      this.topicTemp.parent_id = row.parent_id
      this.topicEditId = row.id
      this.titleTopicDialog = '编辑框架-' + row.title
      this.topicTemp.strategy_id = row.strategy_id
      this.titleTopicDialogVisible = true
      // if (typeof this.$refs.mt !== 'undefined') {
      //   this.$nextTick(() => {
      //     this.$refs.mt.setContent(this.topicTemp.description)
      //   })
      // }
    },
    handleAddTopic() {
      // 编辑模式时，保留原有的strategy_id
      if (this.topicEditId === '' && this.strategy_id) {
        this.topicTemp.strategy_id = this.strategy_id
      }

      // 确保数值类型字段正确转换
      const submitData = {
        ...this.topicTemp,
        star: parseInt(this.topicTemp.star) || 1,
        progress: parseInt(this.topicTemp.progress) || 0,
        ai_paragraph: parseInt(this.topicTemp.ai_paragraph) || 3
      }

      if (this.topicEditId !== '') {
        // 编辑模式 - 只发送修改的字段
        submitData.id = this.topicEditId
        Put(this.topicEditId, submitData).then(response => {
          this.$message.success('修改成功')
          this.getList()
          this.titleTopicDialogVisible = false
          this.topicEditId = ''
        }).catch(e => {
          console.error('修改失败:', e)
          this.$message.error('修改失败: ' + (e.response?.data?.msg || e.message || '未知错误'))
        })
      } else {
        // 新增模式
        AddTopic(submitData).then(response => {
          this.$message.success('保存成功')
          this.getList()
          this.titleTopicDialogVisible = false
        }).catch(e => {
          console.error('保存失败:', e)
          this.$message.error('保存失败: ' + (e.response?.data?.msg || e.message || '未知错误'))
        })
      }
    },
    handleCleanTopicForm() {
      this.topicTemp.title = ''
      this.topicTemp.description = '# 一级标题(h1)\n## 二级标题(h2)\n### 三级标题(h3)\n#### 四级标题h4\n注意#号和内容要有空格,每行一个标题\n' +
            'AI内容+随机抓取内容:{random}\n纯随机抓取:{random-only}\n关键词替换:[keyword]'
      this.topicTemp.keyword = this.keyword
      this.topicTemp.tag = ''
      this.topicTemp.progress = 0
      this.topicTemp.star = 1
      this.topicTemp.ai_paragraph = 3
      this.topicTemp.category_id = '3'
      this.topicTemp.web_id = ''
      this.topicTemp.writer_id = ''
      this.topicTemp.parent_id = ''
      this.topicTemp.serp_crawl = false
      this.topicTemp.serp_finished = false
      this.topicTemp.auto_post_account_id = ''
      this.topicTemp.auto_post_category = ''
      this.topicTemp.auto_post_tags = ''
      this.topicEditId = ''
      // if (typeof this.$refs.mt !== 'undefined') {
      //   this.$nextTick(() => {
      //     this.$refs.mt.setContent('')
      //   })
      // }
    },
    handleSaveQuickEditTopic(row, field, t) {
      // 设置row的field字段的值为value
      const data = {
        id: row.id
      }
      // 弹窗输入原因
      if (t === 'rejected') {
        this.rejectReasonRow = row
        this.rejectReasonField = field
        this.rejectReasonValue = t
        this.rejectReason = ''
        this.rejectDialogVisible = true
      } else {
        data[field] = t
        Put(row.id, data).then(response => {
          this.$message.success('修改成功')
          row[field] = t
        }).catch(e => {
          this.$message.error('修改失败')
        })
      }
    },
    handleSaveTopic(row) {
      Put(row.id, row).then(response => {
        this.$message.success('修改成功')
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleOpenReviews(row) {
      const routeData = this.$router.resolve({ name: 'cms.bestreviewhtml', query: { k: row.keyword }})
      console.log(routeData)
      window.open(routeData.href, '_blank')
    },
    handleAddMaterial(row) {
      this.topic_id = row.id
      this.topic_title = '框架素材:[' + row.title + ']'
      this.materialVisible = true
      this.topicmaterialDrawerVisible = true
    },
    handleShowMaterial(row) {
      this.handleAddMaterial(this.topicViewData)
    },
    handleAddPost(row) {
      this.topic_id = row.id
      this.topic_title = '框架:[' + row.title + ']'
      this.postVisible = true
    },
    handleEditPost(row) {
      this.edit_post_id = row.post_id
      this.postEditorVisible = true
      // const link = this.$router.resolve({ name: 'editPostPut', params: { post_id: row.post_id }})
      // window.open(link.href, '_blank')
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    progressToolTips(val) {
      return '完成进度:' + val + '%'
    },
    starToolTips(val) {
      return '星级:' + val
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      if (this.web_id) {
        this.topicTemp.web_id = this.web_id
      }
      if (this.project_id) {
        this.topicTemp.project_id = this.project_id
      }
      this.getList()
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.post__writer_finished && row.progress < 100) {
        if (row.owner_pass) {
          return 'success-row'
        } else {
          return 'warning-row'
        }
      }
      return ''
    },
    handleSelectionChange(rows) {
      this.drawer_data = rows
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleClickEdit(id) {
      const link = this.$router.resolve({ name: 'editPostPut', params: { post_id: id }})
      window.open(link.href, '_blank')
    },
    handleClickView(row) {
      // this.$router.push({ name: 'viewPost', params: { post_id: id }})
      this.topicViewData = row
      this.TopicViewDialogVisible = true
    },
    handleSetProgress(row, progress) {
      row.progress = progress
      Put(row.id, { id: row.id, progress: progress }).then(response => {
        this.$message.success('修改成功')
        const index = this.data.findIndex(x => x.id === row.id)
        this.data.splice(index, 1)
      }).catch(e => {
        this.$message.error('修改失败')
      })
      // this.HanldeEditTopic()
    },
    handleDirectlyEditTopic(row) {
      // this.drawer = false
      this.topicViewData = row
      this.HanldeEditTopic()
    },
    handleClickDelete(row) {
      this.deleteDialogVisible = true
      this.deleteDialogTitle = `确认要删除框架 ${row.title}?`
      this.deleteId = row.id
    },
    handleDeleteConfirm() {
      this.deleteDialogLoading = true
      Delete(this.deleteId)
        .then(res => {
          this.deleteDialogLoading = false
          this.deleteDialogVisible = false
          this.getList()
        }).catch(e => {
          this.deleteDialogLoading = false
        })
    },
    handleClickShare(v, event) {
      const link = this.$router.resolve({
        name: 'viewPost',
        params: {
          post_id: v
        }
      })
      clip(window.location.origin + '/' + link.href, event)
      this.$message({
        message: '复制成功',
        type: 'success',
        duration: 1500
      })
    },
    handleChangePostFinishStatus(row) {
      Put(row.id, JSON.stringify({
        is_finished: row.is_finished,
        put_finished: 1
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: '修改状态成功',
            type: 'success',
            duration: 1000
          })
          this.getList(false)
        })
        .catch(e => {
        })
    },
    queryRejectReasons(queryString, cb) {
      const results = queryString
        ? this.rejectReasons.filter(item => item.value.indexOf(queryString) > -1)
        : this.rejectReasons
        // 调用callback返回建议列表的数据
      cb(results)
    },
    handleSelectReason(item) {
      this.rejectReason = item.value
    },
    handleRejectConfirm() {
      if (!this.rejectReason) {
        this.$message.warning('请输入驳回原因')
        return
      }

      const data = {
        id: this.rejectReasonRow.id
      }
      data[this.rejectReasonField] = this.rejectReasonValue
      data['review_comment'] = this.rejectReason

      Put(this.rejectReasonRow.id, data).then(response => {
        this.$message.success('修改成功')
        this.rejectReasonRow[this.rejectReasonField] = this.rejectReasonValue
        this.rejectDialogVisible = false
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleTranslateTitle(row) {
      if (!row.title) {
        this.$message.warning('标题为空，无法翻译')
        return
      }
      Translate({ text: row.title, target_language: 'zh' }).then(res => {
        if (res.success && res.data) {
          this.$msgbox({
            title: '翻译结果',
            message: `
              <div style="margin-bottom: 10px;">
                <strong>原文：</strong><br>
                <div style="padding: 8px; background: #f5f5f5; border-radius: 4px; margin: 5px 0;">${row.title}</div>
              </div>
              <div>
                <strong>译文：</strong><br>
                <div style="padding: 8px; background: #e8f4fd; border-radius: 4px; margin: 5px 0; line-height: 1.5;">${res.data}</div>
              </div>
            `,
            dangerouslyUseHTMLString: true,
            showCancelButton: true,
            confirmButtonText: '复制译文',
            cancelButtonText: '关闭',
            customClass: 'translation-dialog'
          }).then(() => {
            // 复制译文到剪贴板
            navigator.clipboard.writeText(res.data).then(() => {
              this.$message.success('译文已复制到剪贴板')
            }).catch(() => {
              this.$message.warning('复制失败，请手动复制')
            })
          }).catch(() => {
            // 用户点击关闭
          })
        } else {
          this.$message.error('翻译失败')
        }
      }).catch(() => {
        this.$message.error('翻译接口调用失败')
      })
    },
    handleGoogleSearch() {
      // 检查是否有选中的文本
      const selectedText = this.getSelectedText()
      if (selectedText) {
        const googleUrl = `https://www.google.com/search?q=${encodeURIComponent(selectedText)}`
        window.open(googleUrl, '_blank')
        this.$message.success(`正在Google搜索: ${selectedText}`)
      } else {
        this.$message.warning('请先选中要搜索的文本内容')
      }
    },
    handleGoogleSearchTitle(title) {
      // 直接搜索指定的标题
      if (title) {
        const googleUrl = `https://www.google.com/search?q=${encodeURIComponent(title)}`
        window.open(googleUrl, '_blank')
        this.$message.success(`正在Google搜索: ${title.substring(0, 30)}${title.length > 30 ? '...' : ''}`)
      } else {
        this.$message.warning('标题为空，无法搜索')
      }
    },
    getSelectedText() {
      try {
        const selection = window.getSelection()
        const selectedText = selection.toString().trim()
        if (selectedText) {
          return selectedText
        }
        // 如果没有选中文本，尝试获取当前鼠标悬停行的标题
        return ''
      } catch (error) {
        console.error('获取选中文本失败:', error)
        return ''
      }
    }
  }
}
</script>

<style scoped>
    .el-header, .el-footer {
      background-color: #fff;
      color: #333;
      text-align: left;
      line-height: 60px;
    }

  .el-aside {
    background-color: #fff;
    border-left: 1px solid #ebeef5;
    color: #333;
    padding-top: 20px;
    padding-left: 10px;
    line-height: 250px;
  }

  .el-main {
    background-color: #fff;
    color: #333;
    text-align: center;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }

  /*.top {*/
  /*padding-left: 20px;*/
  /*padding-right: 20px;*/
  /*margin-bottom: 5px;*/
  /*margin-top: 28px;*/
  /*}*/

  /*.head {*/
  /*width: calc(20% - 70px);*/
  /*}*/

  /*.web {*/
  /*margin-top: 10px;*/
  /*margin-bottom: 10px;*/
  /*display: inline-block;*/
  /*width: 100%;*/
  /*}*/

  .web >>> .el-input {
    min-width: 1200px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .app-container >>> .el-table .warning-row {
      background: oldlace;
    }

    .app-container >>> .el-table .success-row {
      background: #f0f9eb;
    }
    .app-container >>> .el-table .finished-row {
      background: #f0f9eb;
    }

  .mt-detail:hover, .svg-icon:hover {
    cursor: pointer;
  }

  .mt-detail {
    color: #1976d2;
  }

  .mt-dialog >>> .el-dialog {
    margin: 88px auto !important;
  }

  .clearfix ::after {
    content: "";
    clear: both
  }

  .mt-table {
    color: black;
    padding: 20px;
  }
  .mt-pagination {
    float: right;
    margin-top: 10px;
  }

  .mt-top {
    margin: 15px 0;
  }

  .mt-row-btn {
    float: right;
    vertical-align: middle;
    color: white;
  }

  .mt-btn {
    background-color: rgba(0, 0, 0, 0);
    background-image: none;
    border-radius: 1000px;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    border-collapse: collapse;
    border-image-outset: 0px;
    border-image-repeat: stretch;
    border-image-slice: 100%;
    border-image-source: none;
    border-image-width: 1;
    border-left-style: solid;
    border-left-width: 1px;
    border-right-style: solid;
    border-right-width: 1px;
    border-top-style: solid;
    border-top-width: 1px;
    box-sizing: border-box;
    color: #46be8a;
    cursor: pointer;
    display: block;
    float: right;
    font-family: "Helvetica Neue", Helvetica, Tahoma, Arial, "Microsoft Yahei", "Hiragino Sans GB", "WenQuanYi Micro Hei", sans-serif;
    font-size: 14px;
    font-weight: 400;
    height: 26px;
    hyphens: manual;
    line-height: 14px;
    margin-bottom: 0px;
    margin-right: 10px;
    padding: 5px;
    text-align: center;
    text-decoration-color: rgb(82, 96, 105);
    text-decoration-line: none;
    text-decoration-style: solid;
    text-rendering: optimizeLegibility;
    text-size-adjust: 100%;
    touch-action: manipulation;
    transition-delay: 0s, 0s, 0s, 0s;
    transition-duration: 0.2s, 0.2s, 0.2s, 0.2s;
    transition-property: border, color, width, background-color;
    transition-timing-function: linear, linear, linear, linear;
    user-select: none;
    vertical-align: middle;
    visibility: visible;
    white-space: nowrap;
    background: white;
  }

  .mt-btn:hover >>> .mt-icon {
    color: #fff;
  }

  .mt-btn:hover {
    background: #46be8a;
  }

  .danger:hover {
    background-color: #F56C6C;
  }

  .danger {
    color: #F56C6C;
  }

  .default:hover {
    background-color: #62a8ea;
  }

  .default {
    color: #62a8ea;
  }

  .edit:hover {
    background-color: #909399;
  }

  .edit {
    color: #909399;
  }
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 460px;
    height: 400px;
    float: left;
    margin-right: 10px;
  }
  .mt-row-title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: calc(100% - 220px);
    display: inline-block;
    vertical-align: middle;
  }

  .mt-row-btns {
    float: right;
    margin-right: 10px;
    z-index: 10000;
  }
 .app-container >>> .el-slider__runway {
    margin: auto !important;
  }

  .inline-input {
    width: 100%;
  }

  /* 浮动搜索按钮样式 */
  .floating-search-btn {
    position: fixed;
    bottom: 80px;
    right: 30px;
    z-index: 1000;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
  }

  .floating-search-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
  }

</style>
